package com.atguigu.yygh.user.service.impl;

import com.atguigu.yygh.cmn.feignclient.DictFeignClient;
import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.common.utils.JwtHelper;
import com.atguigu.yygh.enums.AuthStatusEnum;
import com.atguigu.yygh.model.user.Patient;
import com.atguigu.yygh.model.user.UserInfo;
import com.atguigu.yygh.model.user.UserLoginRecord;
import com.atguigu.yygh.user.mapper.UserInfoMapper;
import com.atguigu.yygh.user.mapper.UserLoginRecordMapper;
import com.atguigu.yygh.user.service.PatientService;
import com.atguigu.yygh.user.service.UserInfoService;
import com.atguigu.yygh.vo.user.LoginVo;
import com.atguigu.yygh.vo.user.UserAuthVo;
import com.atguigu.yygh.vo.user.UserInfoQueryVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Transactional(rollbackFor = Exception.class)
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {
    @Resource
    private UserInfoMapper userInfoMapper;
    @Resource
    private UserLoginRecordMapper userLoginRecordMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Resource
    private PatientService patientService;

    /**
     * 用户登录功能实现1、验证码先注释，后续校验 2、登录成功生成token，
     *
     * @param loginVo
     * @return
     */
    @Override
    public Map<String, Object> loginUserInfo(LoginVo loginVo) {
        // 获取参数
        String phone = loginVo.getPhone();
        String codePhone = loginVo.getCode(); // 验证码
        String openid = loginVo.getOpenid();

        // 校验参数
        if (StringUtils.isEmpty(phone)) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        // 校验验证码,从redis缓存中获取验证码
        String codeCachRedis = (String) redisTemplate.opsForValue().get("yygh:msm:code:" + phone);
        System.out.println("codeCachRedis = " + codeCachRedis);
        //    CODE_ERROR(206, "验证码错误"),
        if (!codeCachRedis.equals(codePhone)) {
            throw new YyghException(ResultCodeEnum.CODE_ERROR);
        }
        // 绑定手机号码
        UserInfo userInfo = null;
        if (!StringUtils.isEmpty(openid)) {
            userInfo = this.getByOpenid(openid);
            if (null != userInfo) {
                userInfo.setPhone(phone);
                this.updateById(userInfo);
            } else {
                throw new YyghException(ResultCodeEnum.DATA_ERROR);
            }
        }
        // userInfo是null,说明手机直接登录
        if (null == userInfo) {
            // 判断手机号是否已经被注册 ,查询用户信息
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("phone", phone);
            // 获取用户信息
            userInfo = userInfoMapper.selectOne(queryWrapper);
            // 若没有则保存到数据库中
            if (ObjectUtils.isEmpty(userInfo)) {
                userInfo = new UserInfo();
                // userInfo.setName("");
                userInfo.setName(phone);
                userInfo.setNickName(phone);
                userInfo.setPhone(phone);
                userInfo.setStatus(1);
                this.saveOrUpdate(userInfo);
                userInfo = userInfoMapper.selectById(userInfo.getId());
                // 记录登录
                UserLoginRecord userLoginRecord = new UserLoginRecord();
                userLoginRecord.setUserId(userInfo.getId());
                userLoginRecord.setIp(loginVo.getIp());
                userLoginRecordMapper.insert(userLoginRecord);
            }
            // 校验是否被禁用
            if (userInfo.getStatus() == 0) {
                throw new YyghException(ResultCodeEnum.LOGIN_DISABLED_ERROR);
            }
        }
        // 记录登录
        UserLoginRecord userLoginRecord = new UserLoginRecord();
        userLoginRecord.setUserId(userInfo.getId());
        userLoginRecord.setIp(loginVo.getIp());
        userLoginRecordMapper.insert(userLoginRecord);

        // 封装数据,返回页面显示名称
        Map<String, Object> loginMap = new HashMap<>();
        String name = userInfo.getName();
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getNickName();
        }
        if (StringUtils.isEmpty(name)) {
            name = userInfo.getPhone();
        }
        // 使用工具类jwt生成token字符串
        String token = JwtHelper.createToken(userInfo.getId(), name);
        loginMap.put("name", name);

        loginMap.put("token", token);
        // 返回Map集合
        return loginMap;
    }

    @Override
    public UserInfo getByOpenid(String openid) {
        UserInfo userInfo = userInfoMapper.selectOne(new QueryWrapper<UserInfo>().eq("openid", openid));

        return userInfo;
    }

    /**
     * 用户认证设计接口：
     * 1、提交认证
     * 2、上传证件图片
     * 3、获取提交认证信息
     *
     * @param userInfoId
     * @param userAuthVo
     * @return
     */
    @Override
    public String commitUserInfoAuth(Long userInfoId, UserAuthVo userAuthVo) {
        // 获取UserAuthVo 封装的参数信息
        String userInfoAuthVoName = userAuthVo.getName();
        String certificatesNo = userAuthVo.getCertificatesNo();
        String certificatesType = userAuthVo.getCertificatesType();
        String certificatesUrl = userAuthVo.getCertificatesUrl();

        // 根据用户的id进行查询用户信息
        UserInfo userInfo = userInfoMapper.selectById(userInfoId);
        if (ObjectUtils.isEmpty(userInfo)) {
            return "提交认证信息失败";
        }
        // 设置认证信息
        // 认证姓名
        userInfo.setName(userInfoAuthVoName);
        // 其他证明信息
        userInfo.setCertificatesNo(certificatesNo);
        userInfo.setCertificatesType(certificatesType);
        userInfo.setCertificatesUrl(certificatesUrl);
        userInfo.setAuthStatus(AuthStatusEnum.AUTH_RUN.getStatus());
        // 调用mapper进行更新用户信息
        baseMapper.updateById(userInfo);
        return "提交认证信息成功";
    }

    /**
     * 条件查询带分页
     *
     * @param page
     * @param limit
     * @param userInfoQueryVo
     * @return
     */
    @Override
    public IPage<UserInfo> findUserInfoListPage(Long page, Long limit, UserInfoQueryVo userInfoQueryVo) {
        // 对userInfoQueryVo条件值进行非空判断
        String name = userInfoQueryVo.getKeyword();
        Integer authStatus = userInfoQueryVo.getAuthStatus();
        String createTimeBegin = userInfoQueryVo.getCreateTimeBegin();
        String createTimeEnd = userInfoQueryVo.getCreateTimeEnd();
        QueryWrapper<UserInfo> userInfoQueryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(name)) {
            userInfoQueryWrapper.like("name", name).like("nick_name", name);
        }
        if (!StringUtils.isEmpty(authStatus)) {
            userInfoQueryWrapper.eq("auth_status", authStatus);
        }
        if (!StringUtils.isEmpty(createTimeBegin)) {
            userInfoQueryWrapper.ge("create_time", createTimeBegin);
        }
        if (!StringUtils.isEmpty(createTimeEnd)) {
            userInfoQueryWrapper.ge("create_time", createTimeEnd);
        }

        // 封装分页条件
        IPage<UserInfo> userInfoPage = new Page<>(page, limit);
        // 调用mapper进行分页查询
        IPage<UserInfo> userInfoIPage = userInfoMapper.selectPage(userInfoPage, userInfoQueryWrapper);
        // 把编号等信息进行转换封装
        userInfoIPage.getRecords().stream().forEach(this::packageUserInfo);

        // 返回分页数据
        return userInfoIPage;
    }

    /**
     * 通过用户Id查看详情
     *
     * @param userInfoId
     * @return
     */
    @Override
    public Map<String, Object> show(Long userInfoId) {
        // 创建map用于封装数据
        Map<String, Object> resultMap = new HashMap<>();

        // 根据userInfoId查询用户信息
        UserInfo userInfo = userInfoMapper.selectById(userInfoId);
        UserInfo packageUserInfo = this.packageUserInfo(userInfo);

        // 根据userInfoId进一步查询就诊人信息
        List<Patient> patientList = patientService.findAllPatient(userInfoId);

        // 封装map集合中
        resultMap.put("userInfo", packageUserInfo);
        resultMap.put("patientList",patientList);
        // 返回map集合
        return resultMap;
    }

    /**
     * 认证审批
     *
     * @param userId
     * @param authStatus 2：通过 -1：不通过
     */
    @Override
    public void approval(Long userId, Integer authStatus) {
        if (authStatus==-1||authStatus==2){
            UserInfo userInfo = userInfoMapper.selectById(userId);
            userInfo.setAuthStatus(authStatus);
            userInfoMapper.updateById(userInfo);
        }
    }

    /**
     * 封装编号对应的userInfo的信息
     *
     * @param userInfo
     * @return
     */
    private UserInfo packageUserInfo(UserInfo userInfo) {
        // 处理用户状态
        String statusString = userInfo.getStatus().equals("0") ? "锁定" : "正常";
        userInfo.getParam().put("statusString", statusString);
        //处理认证状态的编码
        userInfo.getParam().put("authStatusString", AuthStatusEnum.getStatusNameByStatus(userInfo.getAuthStatus()));

        return userInfo;
    }


}
